#include "../include/read_json.h"
// 区分系统位数读取
#include <stdint.h>
#if __WORDSIZE == 64
  #define PRINTF_SIZEOF_FORMAT "%lu"
#else
  #define PRINTF_SIZEOF_FORMAT "%u"
#endif
/*
* 要以末尾的 , 来判断当前是否为最后一项
*/

int cut_json_array_str(dynamic_array_t* dynamic_array, const char* input_buf, const unsigned int input_len)
{
    unsigned int i = 0, j = 0, json_num = 0;
    unsigned int before_num = 0, later_num = 0;
    const char* buf_str = NULL;

    // RJ_LOG_DEBUG("cut_json_array_str() input_len = %u: %s\n", input_len, input_buf);
    // 如果不是[ 或者 { 开头； （不是json字符串）
    if ((input_buf[i] != '[') && (input_buf[i] != '{')) {
        return E_READJSON_INPUTSTR;
    }

    // 输入流中未使用数组格式来包含json
    if (input_buf[i] == '{') {
        // 记录前花括号的个数(‘{’)，用于多层嵌套时，对应后花括号('}')
        before_num++;
        // 记录位置
        buf_str = input_buf + i;
        j = i;
        // 为了包含'{'，所以此处先记录位置再做偏移；
        i++;
        while (i < input_len) {
            if (input_buf[i] == '{') {
                before_num++;
            }
            if (input_buf[i] == '}') {
                later_num++;
                if (before_num == later_num) {
                    // 为了包含'}'，i需要再往后偏移一个位置
                    i++;
                    break;
                }
            }
            i++;
        }

        // 校验动态数据空间是否足够存下json项
        if (dynamic_array->dimension[0] < (i - j)) {
            RJ_LOG_WARNING("cut_json_array_str() json_str need %d Bytes, but dynamic_array only %d Byte.\n", (i - j), dynamic_array->dimension[0]);
            return E_READJSON_INSUFFICIENT_SPACE;
        }
        if (dynamic_array->dimension[1] < json_num) {
            RJ_LOG_WARNING("cut_json_array_str() json_str_num need %d, but dynamic_array only %d.\n", json_num, dynamic_array->dimension[1]);
            return E_READJSON_INSUFFICIENT_SPACE;
        }

        // 保证空间纯净
        memset(dynamic_array->mem_start + (json_num * dynamic_array->dimension[0]), 0, dynamic_array->dimension[0]);
        // 将匹配到的一项json拷贝到动态数组中
        memcpy(dynamic_array->mem_start + (json_num * dynamic_array->dimension[0]), buf_str, i - j);
        // (dynamic_array->mem_start + (json_num * dynamic_array->dimension[0]))[i - j] = '\0';
        json_num++;
    }
    else if (input_buf[i] == '[') {
        while (i < input_len && input_buf[i] != ']') {
            before_num = 0; later_num = 0;
            int case_flag = 0;
            // [{"a":1, "b":2}, {"c":3}]
            // 当数组内容为["first", "second"] 时,也是合法的json字符串,需要将"first"和"second"提取到value中
            while (input_buf[i] != '{' && input_buf[i] != ']' && input_buf[i] != '"') {
                i++;
            }
            if (input_buf[i] == ']') {
                return json_num;
            }
            else if (input_buf[i] == '{') {
                before_num++;
            }
            else if (input_buf[i] == '"') {
                case_flag = 1;
            }
            buf_str = input_buf + i;
            j = i;
            i++;
            while (i < input_len) {
                if (input_buf[i] == '{') {
                    before_num++;
                }
                else if (before_num && input_buf[i] == '}') {
                    later_num++;
                    if (before_num == later_num) {
                        i++;
                        break;
                    }
                }
                else if (case_flag && input_buf[i] == '"') {
                    i++;
                    break;
                }
                i++;
            }

            // 校验动态数据空间是否足够存下json项
            if (dynamic_array->dimension[0] < (i - j)) {
                RJ_LOG_WARNING("cut_json_array_str() json_str need %d Bytes, but dynamic_array only %d Byte.\n", (i - j), dynamic_array->dimension[0]);
                return E_READJSON_INSUFFICIENT_SPACE;
            }
            if (dynamic_array->dimension[1] < json_num) {
                RJ_LOG_WARNING("cut_json_array_str() json_str_num need %d, but dynamic_array only %d.\n", json_num, dynamic_array->dimension[1]);
                return E_READJSON_INSUFFICIENT_SPACE;
            }

            // 保证空间纯净
            memset(dynamic_array->mem_start + (json_num * dynamic_array->dimension[0]), 0, dynamic_array->dimension[0]);
            memcpy(dynamic_array->mem_start + (json_num * dynamic_array->dimension[0]), buf_str, i - j);
            // (dynamic_array->mem_start + (json_num * dynamic_array->dimension[0]))[i - j] = '\0';
            json_num++;
        }
    }
    return json_num;
}


// 将完整的json字符串，分割为单独的key-value项
int cut_json_str(dynamic_array_t* output_buf, const char* input_json)
{
    int i = 0, k = 0;
    int start_flag = 0, brackets_num = 0;
    unsigned int pos1 = 0;
    
    // RJ_LOG_DEBUG("---cut_json_str() input: %s\n", input_json);
    // 遍历输入字符串
    for (i = 0; input_json[i] != '\0'; i++) {

        // 如果是 {      则需要单独存储起来
        if ((start_flag == 0) && ((input_json[i] == '{') || (input_json[i] == '}')) ) {
            // 校验动态数据空间是否足够存下json项
            if (output_buf->dimension[0] < 1) {
                RJ_LOG_WARNING("cut_json_str() json key_value need %d Bytes, but dynamic_array only %d Byte.\n", 1, output_buf->dimension[0]);
                return E_READJSON_INSUFFICIENT_SPACE;
            }
            if (output_buf->dimension[1] < k) {
                RJ_LOG_WARNING("cut_json_str() json key_value num need %d, but dynamic_array only %d.\n", k, output_buf->dimension[1]);
                return E_READJSON_INSUFFICIENT_SPACE;
            }
            memset(output_buf->mem_start + (k * output_buf->dimension[0]), 0, output_buf->dimension[0]);    
            memcpy(output_buf->mem_start + (k * output_buf->dimension[0]), input_json + i, 1);
            k++;
        }

        // 找到第一个" （起始位置）
        if ((start_flag == 0) && (input_json[i] == '"')) {
            start_flag = 1;
            // 记录位置
            pos1 = i;
        }
        /*  找到起始位置后，再找到每项元素的分割符（,）   */ 
        // 如果中途遇到 [ 或 {  则需要忽略 [] 或 {} 中的分隔符（,）
        if ((start_flag == 1) && ((input_json[i] == '{') || (input_json[i] == '['))) {
            // 可能会有多级嵌套，需要累加
            brackets_num++;
        }
        if ((brackets_num > 0) && ((input_json[i] == '}') || (input_json[i] == ']'))) {
            brackets_num--;
            // 括号计数匹配完，找到该项成员
            if (brackets_num == 0) {            
                // 校验动态数据空间是否足够存下json项
                if (output_buf->dimension[0] < ((i - pos1) + 1)) {
                    RJ_LOG_WARNING("cut_json_str() json key_value need %d Bytes, but dynamic_array only %d Byte.\n", ((i - pos1) + 1), output_buf->dimension[0]);
                    return E_READJSON_INSUFFICIENT_SPACE;
                }
                if (output_buf->dimension[1] < k) {
                    RJ_LOG_WARNING("cut_json_str() json key_value num need %d, but dynamic_array only %d.\n", k, output_buf->dimension[1]);
                    return E_READJSON_INSUFFICIENT_SPACE;
                }
                // 保证输出空间纯净
                memset(output_buf->mem_start + (k * output_buf->dimension[0]), 0, output_buf->dimension[0]);
                // 记录该成员，找到成员数累加
                // 此处复制的长度+1（需要最后的}）
                memcpy(output_buf->mem_start + (k * output_buf->dimension[0]), input_json + pos1, ((i - pos1) + 1));
                // RJ_LOG_DEBUG("---i[%d] pos[%d]:%s\n", i, pos1, output_buf->mem_start + (k * output_buf->dimension[0]));
                k++;
                // 清除start_flag，寻找下一项成员
                start_flag = 0;
            }
        }
        // 无{嵌套类型，需要找到, 作为该项成员的结束特征值（最后一项是后花括号 结尾）
        if ((start_flag == 1) && (brackets_num == 0) && \
        ((input_json[i] == ',') || (input_json[i] == '}'))) {
            // 校验动态数据空间是否足够存下json项
            if (output_buf->dimension[0] < ((i - pos1) + 1)) {
                RJ_LOG_WARNING("cut_json_str() json key_value need %d Bytes, but dynamic_array only %d Byte.\n", ((i - pos1)), output_buf->dimension[0]);
                return E_READJSON_INSUFFICIENT_SPACE;
            }
            if (output_buf->dimension[1] < k) {
                RJ_LOG_WARNING("cut_json_str() json key_value num need %d, but dynamic_array only %d.\n", k, output_buf->dimension[1]);
                return E_READJSON_INSUFFICIENT_SPACE;
            }
            // 记录该成员，找到成员数累加
            // 此处复制的长度不用+1（不复制最后的,或者}）
            memset(output_buf->mem_start + (k * output_buf->dimension[0]), 0, output_buf->dimension[0]);
            memcpy(output_buf->mem_start + (k * output_buf->dimension[0]), input_json + pos1, ((i - pos1)));
            // RJ_LOG_DEBUG("---i[%d] pos[%d]:%s\n", i, pos1, output_buf->mem_start + (k * output_buf->dimension[0]));
            k++;
            // 清除start_flag，寻找下一项成员
            start_flag = 0;

            // 将括号保留（以便区分层级关系）
            if (input_json[i] == '}') {
                // 校验动态数据空间是否足够存下json项
                if (output_buf->dimension[0] < 1) {
                    RJ_LOG_WARNING("cut_json_str() json key_value need %d Bytes, but dynamic_array only %d Byte.\n", 1, output_buf->dimension[0]);
                    return E_READJSON_INSUFFICIENT_SPACE;
                }
                if (output_buf->dimension[1] < k) {
                    RJ_LOG_WARNING("cut_json_str() json key_value num need %d, but dynamic_array only %d.\n", k, output_buf->dimension[1]);
                    return E_READJSON_INSUFFICIENT_SPACE;
                }
                memset(output_buf->mem_start + (k * output_buf->dimension[0]), 0, output_buf->dimension[0]);     
                memcpy(output_buf->mem_start + (k * output_buf->dimension[0]), input_json + i, 1);
                // RJ_LOG_DEBUG("---i[%d] pos[%d]:%s\n", i, pos1, output_buf->mem_start + (k * output_buf->dimension[0]));
                k++;
            }
        }
    }

    // 原样返回
    if (start_flag == 1) {
        // 校验动态数据空间是否足够存下json项
        if (output_buf->dimension[0] < (i - pos1)) {
            RJ_LOG_WARNING("cut_json_str() json key_value need %d Bytes, but dynamic_array only %d Byte.\n", (i - pos1), output_buf->dimension[0]);
            return E_READJSON_INSUFFICIENT_SPACE;
        }
        if (output_buf->dimension[1] < k) {
            RJ_LOG_WARNING("cut_json_str() json key_value num need %d, but dynamic_array only %d.\n", k, output_buf->dimension[1]);
            return E_READJSON_INSUFFICIENT_SPACE;
        }
        // 保证输出空间纯净
        memset(output_buf->mem_start + (k * output_buf->dimension[0]), 0, output_buf->dimension[0]);
        // 记录该成员，找到成员数累加
        // 此处复制的长度不用+1（不复制最后的,或者}）
        memcpy(output_buf->mem_start + (k * output_buf->dimension[0]), input_json + pos1, (i - pos1));
        // RJ_LOG_DEBUG("---i[%d] pos[%d]:%s\n", i, pos1, output_buf->mem_start + (k * output_buf->dimension[0]));
        k++;
    }

    return k;
}


int cut_json_member(json_member_t* json_member, const char* input_json_unit)
{

    int i = 0;
    int key_start_pos = -1, key_end_pos = -1, value_start_pos = -1, value_end_pos = -1;
    int value_flag = 0; // 如果value是复杂结构："key" : { "kye1": "value1", "k2":"v2" } 或 "key" : [ {"kye1": "value1"}, {"k2":"v2"} ]
    int brackets_num = 0;
    // int input_len = strlen(input_json_unit);
    // memset(json_member, 0, sizeof(json_member_t));

    // 取出key的部分
    while (input_json_unit[i] != '\0') {
        // 有可能前面为{、[、} 需要保留
        if (('{' == input_json_unit[i]) || ('[' == input_json_unit[i]) || ('}' == input_json_unit[i])) {
            // 校验空间是否足够保存
            if (sizeof(json_member->key) < 1) {
                RJ_LOG_WARNING("cut_json_member json_member->key need %d Bytes, but available "PRINTF_SIZEOF_FORMAT" Bytes.\n", 1, sizeof(json_member->key));
                return E_READJSON_INSUFFICIENT_SPACE;
            }
            memset(json_member->key, 0, sizeof(json_member->key));
            memcpy(json_member->key, input_json_unit + i, 1);
        }
        // 匹配到 " 所在位置
        else if ('"' == input_json_unit[i]) {
            // 记录key开始位置
            if (key_start_pos == -1) {
                key_start_pos = i;
                i++;
                continue;
            }
            // 转义符后面的"不做判断（做拷贝key时 需要去掉转义符(\) - 暂未实现）
            if ((i > 0) && ('\\' == input_json_unit[i-1])) {
                i++;
                continue;
            }
            // 记录key结束的位置 (后面的")
            if (key_start_pos != -1) {
                key_end_pos = i;
                // 校验空间是否足够保存
                if (sizeof(json_member->key) < ((key_end_pos - key_start_pos) + 1)) {
                    RJ_LOG_WARNING("cut_json_member json_member->key need %d Bytes, but available "PRINTF_SIZEOF_FORMAT" Bytes.\n", (key_end_pos - key_start_pos) + 1, sizeof(json_member->key));
                    return E_READJSON_INSUFFICIENT_SPACE;
                }
                // 保证空间纯净
                memset(json_member->key, 0, sizeof(json_member->key));
                memcpy(json_member->key, input_json_unit + key_start_pos, (key_end_pos - key_start_pos) + 1);
                // RJ_LOG_DEBUG("key[%s].\n", json_member->key);
                i++;
                break;
            }
        }
        i++;
    }

    // 找到分隔符
    while (input_json_unit[i] != '\0') {
        if (':' == input_json_unit[i]) {
            i++;
            break;
        }
        i++;
    }

    // 跳过:后面空白的字符（空格，换行）
    while (input_json_unit[i] != '\0') {
        if ((input_json_unit[i] != ' ') && (input_json_unit[i] != '\n')) {
            break;
        }
        i++;
    }
    // RJ_LOG_DEBUG("---i[%d][%c].\n",i, input_json_unit[i]);
    // 取出value部分    
    while (input_json_unit[i] != '\0') {
        // 判断value是何种类型 {...} or "..." or 180
        // 判断 冒号后第一个有效字符是否为前花括号{ 或 数组[（value是复杂结构）
        if ((input_json_unit[i] == '{') || (input_json_unit[i] == '[')) {
            // 记录value的开始位置
            if (value_start_pos == -1) {
                value_start_pos = i;
            }
            // 标记该value是复杂结构，需要再次解析
            value_flag = 1;
            brackets_num++;
            i++;
            while (brackets_num && (input_json_unit[i] != '\0')) {
                if ((input_json_unit[i] == '{') || (input_json_unit[i] == '[')) {
                    brackets_num++;
                }
                else if ((input_json_unit[i] == '}') || (input_json_unit[i] == ']')) {
                    brackets_num--;
                }
                i++;
            }
            value_end_pos = i;
            break;
        }
        else if (input_json_unit[i] == '"') {
            // 记录value的开始位置
            if (value_start_pos == -1) {
                value_start_pos = i;
            }
            i++;
            while ((input_json_unit[i] != '"') || (input_json_unit[i-1] == '\\')) {
                i++;
            }
            value_end_pos = i;
            break;
        }
        else {
            // 记录value的开始位置
            if (value_start_pos == -1) {
                value_start_pos = i;
            }
            i++;
            while (input_json_unit[i] != '\0') {
                // 遇到结束符(,)或者空格或者换行就退出while
                if ((input_json_unit[i] == ',') || (input_json_unit[i] == ' ') || (input_json_unit[i] == '\n')) {
                    break;
                }
                i++;
            }

            // 不复制结束符
            value_end_pos = i-1;
            break;
        }
        i++;
    }

    // 保证输出空间纯净
    memset(json_member->value, 0, sizeof(json_member->value));
    if (value_start_pos != -1) {
        // RJ_LOG_DEBUG("value_start_pos[%d] value_end_pos[%d].\n", value_start_pos, value_end_pos);
        // 校验空间是否足够保存
        if (sizeof(json_member->value) < ((value_end_pos - value_start_pos) + 1)) {
            RJ_LOG_WARNING("cut_json_member json_member->value need %d Bytes, but available "PRINTF_SIZEOF_FORMAT" Bytes.\n", (value_end_pos - value_start_pos) + 1, sizeof(json_member->value));
            return E_READJSON_INSUFFICIENT_SPACE;
        }
        memcpy(json_member->value, input_json_unit + value_start_pos, (value_end_pos - value_start_pos) + 1);
        // RJ_LOG_DEBUG("value_flag:%d key:%s value:%s\n", value_flag, json_member->key, json_member->value);
    }

    return value_flag; 

}


int get_str_form_x(char* output_buf, int out_buf_len, char* input_buf, char x)
{
    int i = 0, j = 0;
    // 遍历输入字符串，找到第一个特征符
    while ((input_buf[i] != x) && (input_buf[i] != '\0')) {
        i++;
    }
    // 遍历完输入字符也未找到特征值
    if (input_buf[i] == '\0') {
        // 校验空间是否足够存储
        if (out_buf_len < i) {
            RJ_LOG_WARNING("get_str_form_x output_buf need %d Bytes, but availabel %d Bytes.\n", i, out_buf_len);
            return E_READJSON_INSUFFICIENT_SPACE;
        }
        // 输出空间清理
        memset(output_buf, 0, out_buf_len);
        // 原样返回
        memcpy(output_buf, input_buf, i);
        return i;
    }
    // 找到第一个特征值
    else {
        // 将位置偏移到特征值的后面
        i++;
        // 记录位置
        j = i;
        // 继续遍历输入字符串，找到第二个特征符
        while ((input_buf[j] != x) && (input_buf[j] != '\0')) {
            j++;
        }
        // 没有找到第二个特征值
        if (input_buf[j] == '\0') {
            // 校验空间是否足够存储
            if (out_buf_len < j) {
                RJ_LOG_WARNING("get_str_form_x output_buf need %d Bytes, but availabel %d Bytes.\n", j, out_buf_len);
                return E_READJSON_INSUFFICIENT_SPACE;
            }
            // 输出空间清理
            memset(output_buf, 0, out_buf_len);
            // 原样返回
            memcpy(output_buf, input_buf, j);
            return j;
        }
        // 找到第二个特征值
        else {
            // 校验空间是否足够存储
            if (out_buf_len < (j - i)) {
                RJ_LOG_WARNING("get_str_form_x output_buf need %d Bytes, but availabel %d Bytes.\n", (j - i), out_buf_len);
                return E_READJSON_INSUFFICIENT_SPACE;
            }
            // 输出空间清理
            memset(output_buf, 0, out_buf_len);
            // 返回特征值中间的字符串
            memcpy(output_buf, input_buf + i, j - i);
            // 返回输出字符串长度
            return j - i;
        }
    }
}


int get_str_form_jsonvalue(char* output_buf, int out_buf_len, const char* input_buf)
{
    int i = 0, j = 0;
    // 遍历输入的字符串，寻找json中value的特征值（引号开始的字符串、纯数字、浮点数、布尔型(true/false)）
    // 此处校验未到达想要的效果（即使value为非法也不能校验，比如非字符串的asdasf，也能解析成字符串存入value---待优化）
    /*不是前引号
    不是数字0-9 和 负号
    不是t开始或者f开始*/
    while ((input_buf[i] != '"') && \
    !(('0' <= input_buf[i] && input_buf[i] <= '9') || (input_buf[i] == '-')) && \
    !((input_buf[i] == 't') || (input_buf[i] == 'f')) && \
    (input_buf[i] != '\0')) {
        i++;
    }
    // 如果value是字符串
    if (input_buf[i] == '"') {
        // i偏移到指向"后面的位置
        i++;
        // 记录现在的位置
        j = i;
        // 寻找第二个"的位置
        while (input_buf[j] != '"' && input_buf[j] != '\0') {
            j++;
        }
        if (input_buf[j] == '"') {
            // 校验空间是否足够存储
            if (out_buf_len < (j - i)) {
                RJ_LOG_WARNING("get_str_form_jsonvalue output_buf need %d Bytes, but availabel %d Bytes.\n", (j - i), out_buf_len);
                return E_READJSON_INSUFFICIENT_SPACE;
            }
            // 输出空间清理
            memset(output_buf, 0, out_buf_len);
            // 将" "之间的内容拷贝到output_buf
            memcpy(output_buf, input_buf + i, j - i);
            // 返回输出字符串长度
            return j - i;
        }
        else {
            // 校验空间是否足够存储
            if (out_buf_len < j) {
                RJ_LOG_WARNING("get_str_form_jsonvalue output_buf need %d Bytes, but availabel %d Bytes.\n", j, out_buf_len);
                return E_READJSON_INSUFFICIENT_SPACE;
            }
            // 输出空间清理
            memset(output_buf, 0, out_buf_len);
            // 无效value，原样输出
            memcpy(output_buf, input_buf, j);
            return j;
        }
    }
    // 纯数字处理（包括浮点数）
    else if (('0' <= input_buf[i] && input_buf[i] <= '9') || (input_buf[i] == '-')) {
        // 小数点计数
        unsigned int decimal_point = 0;
        // 记录现在的位置 (:23456  => j == i == 0)
        j = i;

        // 负数处理
        if (input_buf[i] == '-') {
            j++;
        }

        // 遍历完数字（最多只能有一个小数点）
        while ((('0' <= input_buf[j] && input_buf[j] <= '9') || (input_buf[j] == '.')) && (decimal_point <= 1)) {
            j++;
            if (input_buf[j] == '.') {
                decimal_point++;
            }
        }
        // 校验空间是否足够存储
        if (out_buf_len < (j - i)) {
            RJ_LOG_WARNING("get_str_form_jsonvalue output_buf need %d Bytes, but availabel %d Bytes.\n", (j - i), out_buf_len);
            return E_READJSON_INSUFFICIENT_SPACE;
        }
        // 输出空间清理
        memset(output_buf, 0, out_buf_len);
        // 将数字内容拷贝到output_buf
        memcpy(output_buf, input_buf + i, j - i);
        // 返回输出字符串长度
        return j - i;
    }
    // 布尔类型(true or false)
    else if ((input_buf[i] == 't') || (input_buf[i] == 'f')) {
        if (input_buf[i] == 't') {
            unsigned int true_len = 0;
            // 记录开始位置
            j = i;
            // 保证长度足够
            while (input_buf[i] != '\0') {
                true_len++;
                i++;
            }
            // 字符串长度校验
            if (true_len == (sizeof("true") - 1)){
                // 字符串内容校验
                if (memcmp("true", input_buf + j, true_len) == 0) {
                    // 校验空间是否足够存储
                    if (out_buf_len < sizeof("true")) {
                        RJ_LOG_WARNING("get_str_form_jsonvalue output_buf need "PRINTF_SIZEOF_FORMAT" Bytes, but availabel %d Bytes.\n", sizeof("true"), out_buf_len);
                        return E_READJSON_INSUFFICIENT_SPACE;
                    }
                    // 输出空间清理
                    memset(output_buf, 0, out_buf_len);
                    // 将内容拷贝到output_buf
                    memcpy(output_buf, "true", sizeof("true"));
                    // 返回输出字符串长度
                    return sizeof("true");
                }
            }
            memcpy(output_buf, input_buf, true_len);
            return true_len;
        }
        else {            
            unsigned int false_len = 0;
            // 记录开始位置
            j = i;
            // 保证长度足够
            while (input_buf[i] != '\0') {
                false_len++;
                i++;
            }
            // 字符串长度校验
            if (false_len == (sizeof("false") - 1)){
                // 字符串内容校验
                if (memcmp("false", input_buf + j, false_len) == 0) {
                    // 校验空间是否足够存储
                    if (out_buf_len < sizeof("false")) {
                        RJ_LOG_WARNING("get_str_form_jsonvalue output_buf need "PRINTF_SIZEOF_FORMAT" Bytes, but availabel %d Bytes.\n", sizeof("false"), out_buf_len);
                        return E_READJSON_INSUFFICIENT_SPACE;
                    }
                    // 输出空间清理
                    memset(output_buf, 0, out_buf_len);
                    // 将内容拷贝到output_buf
                    memcpy(output_buf, "false", sizeof("false"));
                    // 返回输出字符串长度
                    return sizeof("false");
                }
            }
            // 无效value，原样输出
            memcpy(output_buf, input_buf, false_len);
            return false_len;
        }
    }
    // 无效value，原样输出
    else {
        // 校验空间是否足够存储
        if (out_buf_len < i) {
            RJ_LOG_WARNING("get_str_form_jsonvalue output_buf need %d Bytes, but availabel %d Bytes.\n", i, out_buf_len);
            return E_READJSON_INSUFFICIENT_SPACE;
        }
        // 输出空间清理
        memset(output_buf, 0, out_buf_len);
        memcpy(output_buf, input_buf, i);
        return i;
    }
}


int recursion_decode_jsonvalue(json_member_t* json_member, int json_member_num, const char* input_json_str)
{
    // value是复杂结构，需继续解析
    // 记录进来时的json_member_num
    int json_member_s_num = json_member_num;
    
    // 从json字符串解析出来的key-value项个数（有数组和花括号两种情况）
    if (input_json_str[0] == '[') {
        int json_num = 0, json_array_flag = 0;
        dynamic_array_t json_arr_da;
        if (dynamic_array_init(&json_arr_da, PARAMETER_MAX_NUMBER * PARAMETER_MAX_LENGTH, 2, PARAMETER_MAX_LENGTH, PARAMETER_MAX_NUMBER) < 0) {
            return E_READJSON_DYNAMICARRAY_INIT;
        }
        // 将json数组拆分
        json_num = cut_json_array_str(&json_arr_da, input_json_str, strlen(input_json_str));
        if (json_num < 0) {
            dynamic_array_free(&json_arr_da);
            return json_num;
        }
        memset(json_member + json_member_num, 0, sizeof(json_member[json_member_num]));
        json_member[json_member_num].key[0] = '[';
        json_member_num++;
        json_array_flag = 1;
        // DEBUG print
        // for (int i = 0; i < json_num; i++) {
        //     RJ_LOG_DEBUG("recursion_decode_jsonvalue-json_arr[%02d]:%s\n", i, json_arr_da.mem_start + (i * json_arr_da.dimension[0]));
        // }
        
        {
            dynamic_array_t unit_buf;
            if (dynamic_array_init(&unit_buf, PARAMETER_MAX_NUMBER * PARAMETER_MAX_LENGTH, 2, PARAMETER_MAX_LENGTH, PARAMETER_MAX_NUMBER) < 0) {
                dynamic_array_free(&json_arr_da);
                return E_READJSON_DYNAMICARRAY_INIT;
            }
            for (int i = 0; i < json_num; i++) {
                // 将一项json拆分为每一个条目 => {"a":1, "b":2} => "a":1 和 "b":2
                int uint_num = cut_json_str(&unit_buf, json_arr_da.mem_start + (i * json_arr_da.dimension[0]));

                for (int k = 0; k < uint_num; k++) {
                    json_member_t jm;
                    int ret = 0;
                    // DEBUG print
                    // RJ_LOG_DEBUG("recursion_decode_jsonvalue-json_unit-k[%02d]:%s\n", k, unit_buf.mem_start + (k * unit_buf.dimension[0]));

                    if ( 0 < cut_json_member(&jm, unit_buf.mem_start + (k * unit_buf.dimension[0]))) {
                        
                        // DEBUG print
                        // RJ_LOG_DEBUG("recursion_decode_jsonvalue json_member-[%s]:[%s]\n", jm.key, jm.value);

                        // 将key记录，value填NULL
                        memset(json_member + json_member_num, 0, sizeof(json_member[json_member_num]));
                        ret = get_str_form_x(json_member[json_member_num].key, sizeof(json_member[json_member_num].key), jm.key, '"');
                        if (ret < 0) {
                            dynamic_array_free(&unit_buf);
                            dynamic_array_free(&json_arr_da);
                            return ret;
                        }
                        memset(json_member[json_member_num].value, '\0', PARAMETER_MAX_LENGTH / 2);
                        json_member_num++;

                        // value是复杂结构，需继续解析
                        json_member_num += recursion_decode_jsonvalue(json_member, json_member_num, jm.value);

                    }
                    else {    
                        // DEBUG print
                        // RJ_LOG_DEBUG("json_member-[%s]:[%s]\n", jm.key, jm.value);
                        
                        memset(json_member + json_member_num, 0, sizeof(json_member[json_member_num]));
                        ret = get_str_form_x(json_member[json_member_num].key, sizeof(json_member[json_member_num].key), jm.key, '"');
                        if (ret < 0) {
                            dynamic_array_free(&unit_buf);
                            dynamic_array_free(&json_arr_da);
                            return ret;
                        }
                        ret = get_str_form_jsonvalue(json_member[json_member_num].value, sizeof(json_member[json_member_num].value), jm.value);
                        if (ret < 0) {
                            dynamic_array_free(&unit_buf);
                            dynamic_array_free(&json_arr_da);
                            return ret;
                        }

                        json_member_num++;
                    }
                }
            }
            dynamic_array_free(&unit_buf);
        }
        dynamic_array_free(&json_arr_da);

        if (json_array_flag) {
            memset(json_member + json_member_num, 0, sizeof(json_member[json_member_num]));
            json_member[json_member_num].key[0] = ']';
            json_member_num++;
        }
    }
    else {
        int v_num;
        dynamic_array_t da;
        if (dynamic_array_init(&da, PARAMETER_MAX_NUMBER * PARAMETER_MAX_LENGTH, 2, PARAMETER_MAX_LENGTH, PARAMETER_MAX_NUMBER) < 0) {
            return E_READJSON_DYNAMICARRAY_INIT;
        }
        v_num = cut_json_str(&da, input_json_str);
        for (int k = 0; k < v_num; k++) {
            int ret = 0;
            json_member_t jm;
            // DEBUG print
            // RJ_LOG_DEBUG("json_unit-k--[%02d]:%s\n", k, da.mem_start + (k * da.dimension[0]));

            if ( 0 < cut_json_member(&jm, da.mem_start + (k * da.dimension[0]))) {
                
                // DEBUG print
                // RJ_LOG_DEBUG("recursion_decode_jsonvalue json_member-[%s]:[%s]\n", jm.key, jm.value);

                // 将key记录，value填NULL
                memset(json_member + json_member_num, 0, sizeof(json_member[json_member_num]));
                ret = get_str_form_x(json_member[json_member_num].key, sizeof(json_member[json_member_num].key), jm.key, '"');                
                if (ret < 0) {
                    dynamic_array_free(&da);
                    return ret;
                }
                memset(json_member[json_member_num].value, '\0', PARAMETER_MAX_LENGTH / 2);
                json_member_num++;

                // value是复杂结构，需继续解析
                json_member_num += recursion_decode_jsonvalue(json_member, json_member_num, jm.value);

            }
            else {    
                // DEBUG print
                // RJ_LOG_DEBUG("json_member-[%s]:[%s]\n", jm.key, jm.value);

                memset(json_member + json_member_num, 0, sizeof(json_member[json_member_num]));
                ret = get_str_form_x(json_member[json_member_num].key, sizeof(json_member[json_member_num].key), jm.key, '"');               
                if (ret < 0) {
                    dynamic_array_free(&da);
                    return ret;
                }
                ret = get_str_form_jsonvalue(json_member[json_member_num].value, sizeof(json_member[json_member_num].value), jm.value);               
                if (ret < 0) {
                    dynamic_array_free(&da);
                    return ret;
                }
                json_member_num++;
            }
        }
        dynamic_array_free(&da);
    }

    return json_member_num - json_member_s_num;
}


int jsonfile_to_keyvalue(json_member_t* json_member, unsigned int member_max_num, const char* input_json_file)
{
    int json_file_max_szie = JSON_NUMBER * JSON_MAX_SIZE;
    char* json_buf;
    int read_len = 0, json_member_num = 0;
    
    // 从文件中将json字符读出并存入json_buf
    FILE_FD json_fd = RJ_FILE_OPEN(input_json_file, O_RDONLY);
    if (IS_ERR(json_fd)) {
        return E_READJSON_OPENFILE;
    }
    
    if ((json_buf = RJ_ZALLOC(json_file_max_szie)) == NULL) {
        RJ_LOG_WARNING("json_buf kmalloc[%d] fail.\n", json_file_max_szie);
        RJ_FILE_CLOSE(json_fd);
        return E_READJSON_MALLOC;
    }
    
    if ((read_len = RJ_READ_FILE(json_fd, json_buf, json_file_max_szie)) < 0) {
        RJ_FREE(json_buf);
        RJ_FILE_CLOSE(json_fd);
        RJ_LOG_WARNING("vfs_read ret[%d].\n", read_len);
        return E_READJSON_READFILE;
    }
    RJ_FILE_CLOSE(json_fd);
    // RJ_LOG_DEBUG("read:%s\n", json_buf);

    json_member_num = jsonbuf_to_keyvalue(json_member, member_max_num, json_buf, read_len);

    RJ_FREE(json_buf);
    return json_member_num;
}

// 将json字符串中的空格与换行删除
int remove_empty(char *out, const char *in, unsigned int in_len)
{
    int i = 0, j = 0;
    if (out == NULL) {
        return 1;
    }
    while (i < in_len) {
        if ((in[i] != ' ') && (in[i] != '\n')) {
            out[j++] = in[i];
        }
        i++;
    }
    return j;
}

// 计算该json字符串需要多少个json_member存储
int calc_json_member_num(const char *in, unsigned int in_len)
{
    int i = 0, j = 0, qutes_flag = 0;
    if (in == NULL) {
        return 1;
    }
    for (;i < in_len; i++) {
        if ((qutes_flag == 0) && (in[i] == '"')) {
            qutes_flag = 1;
            continue;
        }
        if ((qutes_flag == 1) && (in[i] == '"')) {
            qutes_flag = 0;
            continue;
        }
        if ((qutes_flag == 0) && ((in[i] == ':') || (in[i] == '{') || (in[i] == '}') || (in[i] == '[')  || (in[i] == ']') )) {
            j++;
            continue;
        }
    }
    return j;
}

int jsonbuf_to_keyvalue(json_member_t *json_member, unsigned int member_max_num, const char *input_json_str, unsigned int str_len)
{
    char *json_buf = NULL;
    int json_buf_len = 0;
    int json_num = 0, json_member_num = 0;
    int uint_num_sum = 0, ret = 0;
    int json_array_flag = 0;
    dynamic_array_t json_arr;
    dynamic_array_t unit_buf;
    
    if (input_json_str == NULL) {
        ret = E_READJSON_NULLPOINTER;
        goto exit0;
    }

    if ((json_buf = RJ_ZALLOC(str_len)) == NULL) {        
        ret = E_READJSON_MALLOC;
        goto exit0;
    }
    // printf("%s\n", input_json_str);
    // 将输入json字符串中的 空格和回车 去除掉，并将结果输出到json_buf
    json_buf_len = remove_empty(json_buf, input_json_str, str_len);
    // printf("%s\n", json_buf);

    // 计算该json字符串是否能被完整存储
    uint_num_sum = calc_json_member_num(input_json_str, str_len);
    if (member_max_num < uint_num_sum) {
        RJ_LOG_WARNING("input json_str need %d json_member, but now json_member[%d].\n", uint_num_sum, member_max_num);
        ret = E_READJSON_INSUFFICIENT_SPACE;
        goto exit1;
    }

    // 将输出空间初始化
    memset(json_member, 0, sizeof(json_member_t) * member_max_num);

    // 初始化动态数组
    if (dynamic_array_init(&json_arr, JSON_NUMBER * JSON_MAX_SIZE, 2, JSON_MAX_SIZE, JSON_NUMBER) < 0) {
        ret = E_READJSON_DYNAMICARRAY_INIT;
        goto exit1;
    }
    // print_dynamic_info(&json_arr);
    // 将json数组拆分 => [{"a":1, "b":2}, {"c":3, "d":4}] => {"a":1, "b":2} 和 {"c":3, "d":4}
    json_num = cut_json_array_str(&json_arr, json_buf, json_buf_len);
    if (json_num < 0) {
        ret = json_num;
        goto exit2;
    }
    if (json_num > 1) {
        memset(json_member + json_member_num, 0, sizeof(json_member[json_member_num]));
        json_member[json_member_num].key[0] = '[';
        json_member_num++;
        json_array_flag = 1;
    }
    // DEBUG print
    // for (int i = 0; i < json_num; i++) {
    //     RJ_LOG_DEBUG("json_arr[%02d]:%s\n", i, json_arr.mem_start + (i * json_arr.dimension[0]));
    // }

    if (dynamic_array_init(&unit_buf, PARAMETER_MAX_NUMBER * PARAMETER_MAX_LENGTH, 2, PARAMETER_MAX_LENGTH, PARAMETER_MAX_NUMBER) < 0) {
        ret = E_READJSON_DYNAMICARRAY_INIT;
        goto exit2;
    }

    // 解析每个json项
    for (int i = 0; i < json_num; i++) {

        // 将一项json拆分为每一个条目 => {"a":1, "b":{...}} => "a":1 和 "b":{...}
        int uint_num = cut_json_str(&unit_buf, json_arr.mem_start + (i * json_arr.dimension[0]));
        if (uint_num < 0) {
            ret = uint_num;
            goto exit3;
        }

        for (int j = 0; j < uint_num; j++) {
            json_member_t temp_member;
            int cut_json_member_ret = 0;
            // DEBUG print
            // RJ_LOG_DEBUG("json_unit-[%02d]:%s\n", j, unit_buf.mem_start + (j * unit_buf.dimension[0]));
            
            cut_json_member_ret = cut_json_member(&temp_member, unit_buf.mem_start + (j * unit_buf.dimension[0]));
            if (cut_json_member_ret < 0) {
                ret = cut_json_member_ret;
                goto exit3;
            } 
            // 如果解析出来的value是复杂结构（递归计算）
            else if ( cut_json_member_ret > 0) {
                // DEBUG print
                // RJ_LOG_DEBUG("json_member-[%s]:[%s]\n", temp_member.key, temp_member.value);
                // 将key记录，value填NULL
                memset(json_member + json_member_num, 0, sizeof(json_member[json_member_num]));
                get_str_form_x(json_member[json_member_num].key, sizeof(json_member[json_member_num].key), temp_member.key, '"');
                memset(json_member[json_member_num].value, '\0', PARAMETER_MAX_LENGTH / 2);
                json_member_num++;

                // 解析出来的value是复杂结构（递归计算）
                // 输入字符串 将结果解析到json_member_t
                json_member_num += recursion_decode_jsonvalue(json_member, json_member_num, temp_member.value);

            }
            else {
                // DEBUG print
                // RJ_LOG_DEBUG("json_member-[%s]:[%s]\n", temp_member.key, temp_member.value);
                memset(json_member + json_member_num, 0, sizeof(json_member[json_member_num]));
                get_str_form_x(json_member[json_member_num].key, sizeof(json_member[json_member_num].key), temp_member.key, '"');
                get_str_form_jsonvalue(json_member[json_member_num].value, sizeof(json_member[json_member_num].value), temp_member.value);
                json_member_num++;
            }
        }
    }
  
    
    if (json_array_flag) {
        memset(json_member + json_member_num, 0, sizeof(json_member[json_member_num]));
        json_member[json_member_num].key[0] = ']';
        json_member_num++;
    }

    ret = json_member_num;

exit3:
    dynamic_array_free(&unit_buf);
exit2:
    dynamic_array_free(&json_arr);
exit1:
    RJ_FREE(json_buf);
exit0:
    return ret;
}


void readjson_error_code_interpret(int error_code)
{
    switch(error_code) {
        case READJSON_SUCCESS:
            RJ_LOG_WARNING("read json Operation successful.\n");
            break;
        case E_READJSON_OPENFILE:
            RJ_LOG_WARNING("read json: open file fail.\n");
            break;
        case E_READJSON_READFILE:
            RJ_LOG_WARNING("read json: read file fail.\n");
            break;
        case E_READJSON_INPUTSTR:
            RJ_LOG_WARNING("read json: input is not jsonString.\n");
            break;
        case E_READJSON_NULLPOINTER:
            RJ_LOG_WARNING("read json: input is null pointer.\n");
            break;
        case E_READJSON_INSUFFICIENT_SPACE:
            RJ_LOG_WARNING("read json: insufficient space.\n");
            break;
        case E_READJSON_DYNAMICARRAY_INIT:
            RJ_LOG_WARNING("read json: daynamic_arrat init fail.\n");
            break;
        case E_READJSON_MALLOC:
            RJ_LOG_WARNING("read json: malloc fail.\n");
            break;
        default:
            RJ_LOG_INFO("read json the error type(%d) is undefined.\n", error_code);
            break;
    }
}

void readjson_print_json_member(json_member_t *json_member, unsigned int json_num)
{
    int i = 0;
    for (i = 0; i < json_num; i++) {
        RJ_LOG_INFO("key[%s]:value[%s]\n", json_member[i].key, json_member[i].value);
    }
}

